<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Login action.
 * Use session to hold the position and the logined information.
 * 
 * 用户登录的action.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.4
 * 
 * 0.2)  Use the login form instead.
 * 0.3)  Adds the auth code.
 * 0.4)  Sets the 'title' and 'rights' in the session.
 * 		 Records the last logged in time.
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

// Requirements.
require_once INSTALLDIR . '/widgets/slh_form_login.php';

require_once INSTALLDIR . '/classes/User.php';


class LoginAction extends Action
{
	/**
	 * Has some instructions?
	 */
	var $instruction = null;
	
	/**
	 * Login username and password. (remember me?)
	 */
	var $username = null;
	var $password = null;
	var $authcode = null;
	var $rememberme = null;

	/**
	 * Authenticated user.
	 */
	var $authenticatedUser = false;
	
	function title()
	{
		return '登陆';
	}
	
	function prepare($args)
	{
		parent::prepare($args);
		
		// First try the cookie.
		if ($this->authenticatedUser === false) {
			if( !empty($_COOKIE['username']) && !empty($_COOKIE['password'])) {
			 	$this->authenticatedUser = User::authenticateUser($_COOKIE['username'], $_COOKIE['password']);
			 	
			 	if ( !empty($this->authenticatedUser)) {
			 		// Cookie login successfully.
			 		if ( !slh_set_user($this->authenticatedUser)) {
						$this->serverError('设置用户出错.');
					}
					slh_real_login(true);
					
					slh_redirect(slh_action2url('publicnews'), 303);
			 	}
			}
		}
		
		return true;
	}
	
	function handle($args)
	{
		parent::handle($args);
		
// Check if logged in.
		if (slh_is_real_login()) {
			slh_redirect(slh_action2url('publicnews'), 303);
		} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			// CSRF protection.
			$this->checkSessionToken();
			
			try {
				$this->username = $this->getTrimmedArg('username');
				$this->password = $this->getArg('password');
				$this->rememberme = $this->getTrimmedArg('rememberme');
				$this->authcode = $this->getTrimmedArg('authcode');
				
				if (strcmp($this->authcode, $_SESSION['authcode']) != 0) {
					$this->instruction = '验证码出错.';
					$this->showForm();
					return;
				}
				
				$this->authenticatedUser = User::authenticateUser($this->username, md5($this->password));
				
				if (false == $this->authenticatedUser) {
					$this->instruction = '用户或密码错误呃.';
				} else {
					if ( !slh_set_user($this->authenticatedUser)) {
						$this->serverError('设置用户出错.');
					}
					
					// Set the last logged in time.
					$this->authenticatedUser->updateLoggedin();
					
					slh_real_login(true);
					
					// Set the association or profile's title and rights in session.
					$expcilitUser = $this->authenticatedUser->getExpcilitUser();
					if (USER_TYPE_PROFILE == $this->authenticatedUser->type) {
						slh_set_usertitle($expcilitUser->realname);
						slh_set_userrights($expcilitUser->profile_rights);
					} else {
						slh_set_usertitle($expcilitUser->cnname);
						slh_set_userrights($expcilitUser->association_rights);
					}
					
					// Remember me. Set the cookie
					// Swapping XD
					if ('true' == $this->rememberme) {
						setcookie('username', $this->username, time() + 3600*24*7);
         				setcookie('password', md5($this->password), time() + 3600*24*7);
					}
					
					// Clear the authcode.
					unset($_SERVER['authcode']);
					
					slh_redirect(slh_action2url('publicnews'), 303);
				}
			} catch (Exception $e) {
				$this->clientError($e->getMessage());
			}
		}
		
		$this->showForm();
	}
	

	/**
	 * Overrideing the showInnerContent().
	 */
	function showInnerContent()
	{
		$this->element('h3', null, '登陆!');
		$this->element('hr');
		
		// Show the instruction.
		$this->showInstruction();
		
		if ($this->authenticatedUser === false) {
			// Show the login input.
			$form = new LoginForm($this, $this->args);
			$form->show();
		}
		
		$this->element('hr');
	}
	
// Overrided ends //////////////////////////////////////////////////////////////

	/**
	 * Shows the intruction this page.
	 */
	function showInstruction()
	{
		if ($this->instruction) {
			$this->elementStart('div', array('class' => 'cls_div_instruction'));
			$this->instruction($this->instruction);
			$this->elementEnd('div');
		}
	}
	
	/**
	 * Shows the form with some extra operations.
	 */
	function showForm()
	{
		$this->showPage();
	}
}

?>